﻿using System;
using System.Windows;
using System.Windows.Media.Animation;
using GalaSoft.MvvmLight.Messaging;
using Greg.WPF.Utility;
using SessionHunter.Business.Exceptions;
using SessionHunter.DataAccess;
using SessionHunter.Messages;
using SessionHunter.ViewModel;

namespace SessionHunter
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

        /// <summary>
        /// Initializes a new instance of the MainWindow class.
        /// </summary>
        public MainWindow()
        {
            try
            {
                InitializeComponent();
            }
            catch (Exception ex)
            {
                ExceptionMessageBox window = new ExceptionMessageBox(ex, "An exception was raised on startup.");
                window.ShowDialog();
                throw;
            }

            // We need to handle this here, because we cannot inherit from ViewModelBaseWithNotification
            Messenger.Default.Register<MainWindowMessage>(this, NotificationMessageReceived);

            // Lets us open a window from the context of the main window
            Messenger.Default.Register<OpenWindowMessage>(this, OpenWindowNotificationMessageReceived);

            ApplySettingsToView(ViewModelLocator.MainStatic.Options);

            Closing += (s, e) => ViewModelLocator.Cleanup();
        }

        /// <summary>
        /// When messages are raised by the various ViewModels, they are received here to be processed
        /// </summary>
        /// <param name="msg">The message received.</param>
        protected void NotificationMessageReceived(MainWindowMessage msg)
        {
            logger.Info("MainWindows received message {0}", msg.Message.ToString());

            switch (msg.Message)
            {
                case MainWindowMessage.MessageAction.References_Attention:
                    Storyboard s = (Storyboard)TryFindResource("btnReferences_Attention");
                    s.Begin();
                    break;
                case MainWindowMessage.MessageAction.Clear_SessionList:
                    // Clear out the current items and remove the focus so we have to force a manual refresh
                    listSession.SelectedItem = null;
                    break;
                default:
                    throw new UnhandledCaseException(msg.Message);
            }
        }

        /// <summary>
        /// Opens the view in the context of this view.
        /// </summary>
        /// <param name="msg">The message with the view to open.</param>
        protected void OpenWindowNotificationMessageReceived(OpenWindowMessage msg)
        {
            if (msg == null || msg.View == null)
                return;

            var window = msg.View;
            logger.Debug("Received message to open a window of type " + window.GetType().Name);

            window.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            window.Owner = this;

            if (msg.Modal)
                window.ShowDialog();
            else
                window.Show();
        }

        /// <summary>
        /// Applies the initial settings to the UI.
        /// </summary>
        /// <param name="options">The options to initially set the values.</param>
        private void ApplySettingsToView(ApplicationOptions options)
        {
            // If we have a fixed number of sessions, set the value
            if (options.NumberOfSessions == -1)
            {
                cbNumberOfSessionsAll.IsChecked = true;
                tbNumberOfSessions.Text = "";
            }
            else
            {
                cbNumberOfSessionsAll.IsChecked = false;
                tbNumberOfSessions.Text = options.NumberOfSessions.ToString();
            }

            cbShowCreateExpires.IsChecked = options.ShowCreateExpires;
            cbShowLockInfo.IsChecked = options.ShowLockInfo;

            // Application parameter            
            cbShowApplication.IsChecked = options.Application;

            // Order By paramater
            switch (options.OrderBy)
            {
                case ApplicationOptions.OrderByParameter.SessionId:
                    rbSessionOrderBySessionId.IsChecked = true;
                    break;
                case ApplicationOptions.OrderByParameter.LargestSession:
                    rbSessionOrderByLargest.IsChecked = true;
                    break;
                case ApplicationOptions.OrderByParameter.CreateDateMostRecent:
                    rbSessionOrderByCreateDateMost.IsChecked = true;
                    break;
                case ApplicationOptions.OrderByParameter.CreateDateLeastRecent:
                    rbSessionOrderByCreateDateLeast.IsChecked = true;
                    break;
                default:
                    throw new UnhandledCaseException(options.OrderBy);
            }
        }

        private void listSession_Loaded(object sender, RoutedEventArgs e)
        {
            ViewModelLocator.MainStatic.DefineColumns(listSession);
        }

        private void TabControl_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            ViewModelLocator.MainStatic.BroadcastApplicationOptionsChange();
        }
    }
}